package cn.edu.nju.ws.sview.views.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;

import cn.edu.nju.ws.sview.LogManagement;
import cn.edu.nju.ws.sview.cache.UserNameIDCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;

/**
 * 管理view的流行度，view的删除操作
 * 
 * 流行度增删原则：只考虑增加view历史使用次数
 * 
 * 删除一个view访问历史次数操作须处理：
 *    1.view 中use_times次数为0
 *    
 * 更新view访问频率需要
 *    1.更新view 中use_times
 *    
 * 删除一个view需要
 * 	  1.删除class_views中有关该view信息
 *    2.删除user_view_visit_control中有关该view信息
 *    3.删除view_dm中该view的记录
 *    4.删除view_favor中该view的记录
 *    5.删除view_trash中该view的记录
 *    6.删除view_ref中引用该view的记录
 *    7.删除view_ref中该view引用记录
 *    8.删除user_view表中的记录
 *    8.删除view表中该view

 * @author gongsaisai
 *
 */
public class ViewManagement extends Management{
	public final static String CLEAR_ENTITY_POPULARITY = "clear_view_pop";

	private static ViewManagement INSTANCE = null;

	private ViewManagement() {

	}

	public static synchronized ViewManagement getInstance() {
		if (INSTANCE == null)
			INSTANCE = new ViewManagement();
		return INSTANCE;
	}

	public static void  storeUserVisit(String userName,int etype,int eid, String lang, int viewID) {
		if(viewID<=0)
			return;
		int userID = 0;
		if (userName != null) {
			try {
				userID = UserNameIDCache.getInstance().getUserID(userName);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		LogManagement.storeLogVisit(userID, etype, eid, viewID, lang);
		
		int status = checkStatus(userID, Management.CONTROL_VIEW_TYPE,0,viewID);
		if (status != EntityManagement.VISITED_COUNT_INVALID) {
			ViewManagement.storeVisitInControl(userID, Management.CONTROL_VIEW_TYPE, 0, viewID);
			userVisit(userID, viewID);
		}
	}
/*
	private void userVisit(int viewID) {
		try {

			Connection con = DBConnectionFactory.getConnection();

			PreparedStatement user_visit_stmt = con
					.prepareStatement("update view set use_times = use_times+1 where id=?");
			user_visit_stmt.setInt(1, viewID);
			user_visit_stmt.executeUpdate();
			user_visit_stmt.close();

			con.close();

		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
*/
	
	private static void userVisit(int userId, int viewId){
		 try {
				Connection con = DBConnectionFactory.getConnection();
				Statement stmt = con.createStatement();
				int date = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)-1;
				PreparedStatement user_day_visit_stmt = con.prepareStatement(
						"insert into user_day_view_visit(user_id,view_id,date,times_recent) " +
						"values(?,?,?,?) on duplicate key update times_recent=times_recent + 1");
				user_day_visit_stmt.setInt(1, userId) ;
				user_day_visit_stmt.setInt(2, viewId);
				int times = 1;
				user_day_visit_stmt.setInt(3,date);
				user_day_visit_stmt.setInt(4, times);
				user_day_visit_stmt.executeUpdate();
				user_day_visit_stmt.close();
				
				PreparedStatement user_visit_stmt = con
						.prepareStatement("update view set use_times = use_times+1 where id=?");
				user_visit_stmt.setInt(1, viewId);
				user_visit_stmt.executeUpdate();
				user_visit_stmt.close();

				con.close();
				
				
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void clearViewPopularity(int viewID) {
		try {
			Connection con = DBConnectionFactory.getConnection();
			Statement stmt = con.createStatement();
			stmt.executeUpdate(String.format(
					"update view set use_times=0 where id=%d ", viewID));
			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void clearViewPopularityAll() {
		try {
			Connection con = DBConnectionFactory.getConnection();
			Statement stmt = con.createStatement();
			stmt.executeUpdate("update view set use_times=0");
			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 删除一个以viewID标识的view的所有相关信息
	 * 
	 * @param viewID
	 *            . view id
	 * @return. 删除是否完全成功
	 */
	public boolean deleteView(int viewID) {
		boolean flag = true;


		try {
			Connection con = DBConnectionFactory.getConnection();
			Statement stmt = con.createStatement();

			stmt.executeUpdate(String.format(
					"delete from class_views where viewId=%d", viewID));
			stmt.executeUpdate(String.format(
					"delete from user_view_visit_control where view_id=%d",
					viewID));
			stmt.executeUpdate(String.format(
					"delete from view_dm where view_id=%d", viewID));
			stmt.executeUpdate(String.format(
					"delete from view_favor where view_id=%d", viewID));
			stmt.executeUpdate(String.format(
					"delete from view_trash where view_id=%d", viewID));
			stmt.executeUpdate(String.format(
					"delete from view_ref where from_view_id=%d", viewID));
			stmt.executeUpdate(String.format(
					"delete from user_view where view_id=%d", viewID));
			stmt.executeUpdate(String.format(
					"delete from view_ref where to_view_id=%d", viewID));
			stmt.executeUpdate(String.format("delete from view where id=%d",
					viewID));

			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			flag = false;
			e.printStackTrace();
		}

		return flag;
	}
}
